// 路由前置守卫
import router from '@/router'
import store from '@/store'
import { asyncRoutes } from '@/router'
// 设置白名单
const whiteList = ['/login', '/404']
// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

router.beforeEach(async(to, from, next) => {
  // 获取token
  const token = store.getters.token
  if (token) {
    if (!store.state.user.userInfo.permissions) {
      // 获取用户的信息
      const { menus, permissions } = await store.dispatch('user/getUserInfo')
      console.log('meaus', menus)
      console.log('permissions', permissions)

      const firstRoutePerms = getFirstRoutePerms(permissions)
      console.log('一级路由-firstRoutePerms', firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(permissions)
      console.log('二级路由-secondRoutePerms', secondRoutePerms)
      // 根据用户权限点,过滤动态路由
      let newRoutes = []
      if (firstRoutePerms.length === 1 && firstRoutePerms[0] === '*') {
        newRoutes = asyncRoutes
      } else {
        newRoutes = asyncRoutes.filter(item => {
          return firstRoutePerms.includes(item.permission)
        }).map(item => {
          return {
            ...item,
            children: item.children.filter(child => {
              return secondRoutePerms.includes(child.permission)
            })
          }
        })
      }
      console.log('过滤后的路由', newRoutes)
      // 将过滤后的路由添加到路由器中
      newRoutes.forEach(item => {
        router.addRoute(item)
      })

      store.commit('user/updateRoutes', newRoutes)
      next(to.path)
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

